/*
Web: http://www.jsForms.com
Copyright (C) 2008  Igor Demyanov (mailto:Igor.Demyanov@gmail.com)
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
jsForms.Components.IndexPage={
		Init: function()
		{
			console.log(this._Name+':IndexPage.Init');
			jsForms.Components.Component.Init.call(this);
			this.FillComponentList();
			//this.C.expCSS.draggable();
			cssController.Init();
			//cssController.SetCSSClass('Test1');
			return this;
		},
		GenerateOutputCSS:function()
		{
			this.C.outputCSS.val(cssController.GenerateCSSFile());
			this.C.outputTemplate[0].innerHTML = '';
			if (!this.P.SelectComponentDesign) {
				return;
			}
			var templateFile = ['jsForms.Templates.'];
			templateFile.push(this.P.SelectComponent._Type);
			templateFile.push('=\'');
			var templateNew = $('<div/>').append(this.P.SelectComponentDesign)[0].innerHTML;
			templateNew = jsForms.DesignMode.CreateTemplate(templateNew);
			templateNew = templateNew.replace(/'/g,'\\\'').replace(/"/g,'\\"');
			templateFile.push(templateNew);
			templateFile.push('\';');
			this.C.outputTemplate.val(templateFile.join(''));
		},
		selectElement:function()
		{
			  //targetInfo.appendTo(document.body);
			  var mouseDock = $('<div class="dev-tool-dock"/>').appendTo(document.body);
		
			  var lastElement = null;
			  var onMove = function(e)
			  {
					if (lastElement != e.target)
					{
						if (lastElement)
						$(lastElement).removeClass('dev-tool-select-object');
						lastElement = e.target;
					}
					else
					{
						//targetInfo.css({left:e.pageX+10+'px', top:e.pageY+10+'px'});
						mouseDock.css({left:e.pageX+'px',top:e.pageY+'px'});
						return false;
					}        
					var tagName ='';
					var className = '';
					var idName = '';
					if (lastElement)
					{
						tagName = lastElement.tagName;
						className = $(lastElement).attr('class');
						idName = $(lastElement).attr('id');
						$(lastElement).addClass('dev-tool-select-object');
					}
					/*var sText = tagName;
					if (idName!='')
					 sText += '#'+idName;
					 if (className!='')
					 sText += '.'+className;
					targetInfo.text(sText);*/
					return false;
				}
				var onClick = function(e)
				{
					//targetInfo.remove();
					mouseDock.remove();
					this.C.Screen.unbind('mousemove',onMove);
					if (lastElement) {
						$(lastElement).removeClass('dev-tool-select-object');
					}
					e.bubbles = false;
					//selectElement(lastElement);
					return true;
				}
				this.C.Screen.unbind('mousemove').bind('mousemove',onMove);
				mouseDock.bind('click',onClick);
		},
		onClickNewComponent:function()
		{
			var newCompName = this.C.iNewComponentName.val();
			var result = jsForms.DesignMode.CreateEmptyComponent(newCompName,'<div/>');
			if (result )
			{
				alert(result.error);
			}
			else
			{
				this.FillComponentList();
			}
		},
		outputTabSelect:function()
		{
		},
		sourceTabSelect:function()
		{
			this.C.templateSourceEditor.Show();
			if (!this.P.SelectComponentDesign) {
				this.C.templateSourceEditor.SetSource('');
				return;
			}
			var templateNew = $('<div/>').append(this.P.SelectComponentDesign)[0].innerHTML;
			templateNew = jsForms.DesignMode.CreateTemplate(templateNew);
			var items = templateNew.split('>');
			var tabs = '';
			var first = true;
			
			for(var i in items)
			{
				var item = items[i];
				var endTag = item.indexOf('</')!=-1;
				if (endTag)
				{
					tabs = tabs.substr(0,tabs.length-1);
				}
				if (item.indexOf('<')!=-1)
				{
					if (first == true) {
						first = false
						tabs = '\t';
					}
					else {
						items[i] = '\n'+tabs + item;
						if (!endTag) {
							tabs = tabs + '\t';
						}
					}
				}				
			}
			templateNew = items.join('>');//templateNew.replace(/>/g,'>\n');
			this.C.templateSourceEditor.SetSource(templateNew);
		},
		sourceTabDeselect:function()
		{
			if (!this.P.SelectComponent) {				
				return;
			}
			var template = this.C.templateSourceEditor.GetSource();
			template= template.replace(/[\n\t]*/g,'');//replace(/[\n\t]*/g,'');
			jsForms.Templates[this.P.SelectComponent._Type] = template
			this.C.templateSourceEditor.Hide();
			this.ChangeComponent(this.P.SelectComponent._Type);
		},
		bScanCSS_Click:function()
		{
			var cssText = this.C.cssText.val();
			cssController.ParseCSSText(cssText);
			//this.C.CSSList.SetClass('#header');
		},
		ResizeLeftSlider: function()
		{
			console.log(this._Name+':ResizeSlider');
			this.C.mainTabs.css('right',this.C.sRight.width());
		},
		bRunTest_Click:function()
		{
			Tests.ExecuteTests();
		},
		FillComponentList:function()
		{
			this.C.insertComponent.empty();
			this.C.lbComponentList.Clear();
			var icomp = this.C.insertComponent;
			$('<option/>').text('NONE').attr('value','NONE').appendTo(icomp);
			for (var i in jsForms.Components)
			{
				$('<option/>').text(i).attr('value',i).appendTo(icomp);
				this.C.lbComponentList.AddItem(i,i);
			}
		},
		lbComponentList_ChangeSelect:function(item)
		{
			this.ChangeComponent(item.GetId());
		},
		ClearPropAndEvents:function()
		{
			this.C.propertiesList.empty();
			this.C.eventsList.empty();
			if (this.P.DOMInspectorSelected)
			{
				this.P.DOMInspectorSelected.hide();
			}
		},
		CleanUp:function()
		{
			if (this.P.SelectComponent != undefined)
			{
				this.P.SelectComponent.remove();
				delete (this.P.SelectComponent);
			}
			if (this.P.SelectComponentDesign != undefined)
			{
				delete (this.P.SelectComponentDesign);
			}
			if (this.P.DOMInspector != undefined)
			{
				delete(this.P.DOMInspector);
			}
			if (this.P.SelectDOMItemId != undefined)
			{
				delete(this.P.SelectDOMItemId);
			}
		},
		tvComponentDOM_ChangeSelect: function(node){
			if (!this.P.DOMInspectorSelected) {
				this.P.DOMInspectorSelected = $('<div/>').attr('id', 'DOMBGInspector');
			}
			this.P.DOMInspectorSelected.hide();
			this.ClearPropAndEvents();
			if (!node) {
				return
			}
			var id = node.GetId();
			var item = this.P.DOMInspector[id];
			if (!item) {
				return;
			}
			this.Properties.SelectDOMItemId = id;
			this.UpdatePropertyList(item);
			this.UpdateEventList(item);
			this.UpdateCSS(item);
			this.UpdateHighlight(item);
		},
		UpdateCSS:function(item)
		{
			this.C.CSSList.SetObject(item.elementR,item.elementD,this.P.SelectComponent._Type);
		},
		UpdateHighlight:function(item)
		{
			if (!this.P.DOMInspectorSelected) {
				return;
			}
			var el = item.elementR;
			if (!el) {
				return
			}
			
			var off = el.offset();
			var w = el[0].offsetWidth;//);
			var h = el[0].offsetHeight;//);
			this.P.DOMInspectorSelected.css({
				left: off.left + 'px',
				top: off.top + 'px',
				width: w + 'px',
				height: h + 'px'
			}).appendTo(document.body).show();
		},
		UpdateEventList:function(item)
		{
			var eventListC = this.C.eventsList.empty();
			if (!item.componentR || item.componentR._Type == undefined|| item.isRoot==true)
			{
				return;
			}
			
			var list = jsForms.DesignMode.GetEvents(item.componentR._Type,item.elementD);
			for (var i in list)
			{
				var e = jsForms.CreateComponent("EventItem");
				//properties.push(p);
				e.SetName(i);
				var eD = jsForms.DesignMode.GetEvent(item.elementD,i,list[i]);
				e.hide().appendTo(eventListC).Init()
				.SetValueList(jsForms.Components[this.Properties.SelectComponent._Type])
				.SetEventObject(eD)
				.SetTemplateComponent(item.elementD)
				.show();
			};
		},
		DeleteElement_Click:function()
		{
			var id = this.Properties.SelectDOMItemId;
			if (id == undefined)
			{
				return;
			}
			var item = this.Properties.DOMInspector[id];
			if (!item || item.isRoot==true || item.isContent == true) return;
			this.ClearPropAndEvents();
			var tree = this.Components.tvComponentDOM;
			tree.RemoveNode(item.node);

			jsForms.DesignMode.DeleteDOMElement(item.elementD);
			if (item.elementR) {
				item.elementR.remove();
			}
			delete(this.Properties.DOMInspector[id]);
		},
		UpDownManipulation:function(fname)
		{
			var id = this.Properties.SelectDOMItemId;
			if (id == undefined)
			{
				return;
			}
			var item = this.Properties.DOMInspector[id];
			if (!item || !item.elementR) {
				return;
			}

			var prevD = item.elementD[fname]();//.prev();
			var prevR = item.elementR[fname]();//.prev();
			var prev = item.node[fname]();//.prev();
			if (prevD.length == 0)
			{
				return;
			}
			
			if (fname == 'prev') {
				prev.before(item.node);
				prevD.before(item.elementD);
				prevR.before(item.elementR);
			}else
			{
				prev.after(item.node);
				prevD.after(item.elementD);
				prevR.after(item.elementR);
			}
		},
		DownElement_Click:function()
		{
			this.UpDownManipulation('next');
		},
		UpElement_Click:function()
		{
			this.UpDownManipulation('prev');
		},
		InsertElement_Click:function()
		{
			var id = this.Properties.SelectDOMItemId;
			var item = this.Properties.DOMInspector[id];
			if (id == undefined)
			{
				return;
			}
			var item = this.Properties.DOMInspector[id];
			if (!item) {
				return;
			}
			//var newTag = '<div/>';
			//var newTag = '<component/>';
			//var newTag = '<span istext>NewText</span>';
			
			var newTag ='';
			
			var iTag = this.Components.insertTag.val();
			var iComponent = this.Components.insertComponent.val();
			var iText = this.Components.insertText.val();
			
			if (iTag!=undefined && iTag!='-' && iTag !='')
			{
				newTag = newTag+'<'+iTag+'/>';
			}
			if (iText != '' && iText != undefined)
			{
				newTag = newTag+'<span istext>'+iText+'</span>';
			}
			if (iComponent != 'NONE' && iComponent != undefined && iComponent != '')
			{
				newTag = newTag+'<component type="'+iComponent+'"/>';
			}
			//insertText
			//insertComponent
			//this.Components

			if (newTag!='' && item.isRoot!=false && item.isText != true && item.isComponent != true) {
				this.Components.insertTag.val('-');
				this.Components.insertComponent.val('NONE');
				this.Components.insertText.val('');
				$(newTag).appendTo(item.elementD);
				//Update TreeView
				this.Apply_PropertiesClick();
			}
		},
		UpdatePropertyList:function(item)
		{
			var propListC = this.Components.propertiesList;
			propListC.empty();
			//Create 'Name','Type','Text' - DOM Setting
			// NAME
			if (item.isRoot!=true && item.isContent!=true) {
				if (item.isText != true) {
					//Name
					var domName = jsForms.CreateComponent('DOMSettingItem');
					domName.SetName('Name');
					var dS = jsForms.DesignMode.GetDOMSetting(item.elementD, 'Name');
					domName.hide().appendTo(propListC).Init().SetDOMSettingObject(dS).SetTemplateComponent(item.elementD).show();
					if (item.isComponent == true) {
						//Type
						var domName = jsForms.CreateComponent('DOMSettingItem');
						domName.SetName('Type');
						var dS = jsForms.DesignMode.GetDOMSetting(item.elementD, 'Type');
						domName.hide().appendTo(propListC).Init().SetDOMSettingObject(dS).SetTemplateComponent(item.elementD).show();
					}
				}
				if (item.isText == true) {
					// Text
					var domName = jsForms.CreateComponent('DOMSettingItem');
					domName.SetName('Text');
					var dS = jsForms.DesignMode.GetDOMSetting(item.elementD,'Text');
					domName.hide().appendTo(propListC).Init().SetDOMSettingObject(dS)
					.SetRealComponent(item.elementR)
					.SetTemplateComponent(item.elementD).show();
				}
				
				if (item.isComponent != true && item.isContent!=true && item.elementD && item.isText!=true){
					//Tag
					var domM = jsForms.CreateComponent('DOMSettingItem');
					domM._SetEvent('onApply',this,this.Apply_PropertiesClick);
					domM.SetName('Tag');
					var dS = jsForms.DesignMode.GetDOMSetting(item.elementD, 'Tag');
					domM.hide().appendTo(propListC).Init().SetDOMSettingObject(dS).SetTemplateComponent(item.elementD).show();
				}
			}
			if (item.isContent==true)
			{// INTO
					var domM = jsForms.CreateComponent('DOMSettingItem');
					domM._SetEvent('onApply',this,this.Apply_PropertiesClick);
					domM.SetName('In To');
					var dS = jsForms.DesignMode.GetDOMSetting(item.elementD, 'In To');
					domM.hide().appendTo(propListC).Init().SetDOMSettingObject(dS).SetTemplateComponent(item.elementD).show();				
			}
			
			//Create Component properties
			if (!item.componentR || item.componentR._Type == undefined)
			{
				return;
			}
						
			var list = jsForms.DesignMode.GetProperties(item.componentR._Type,item.elementD);
			for (var i in list)
			{
				var p = jsForms.CreateComponent("PropertyItem");
				p.SetName(i);
				var pD = jsForms.DesignMode.GetProperty(item.elementD,i,list[i]);
				p.SetRealComponent(item.componentR);//.SetNoChangeTemplate(true);
				p.hide().appendTo(propListC).Init().SetPropertyObject(pD).SetTemplateComponent(item.elementD).show();
			};
		},
		Apply_PropertiesClick:function()
		{
			if (!this.P.SelectComponentDesign) return;
			var type = this.P.SelectComponent._Type;
			var templateNew = $('<div/>').append(this.P.SelectComponentDesign)[0].innerHTML;
			this.P.SelectComponentDesign.remove();
			jsForms.Templates[type] = jsForms.DesignMode.CreateTemplate(templateNew);
			this.ChangeComponent(type);
		},
		TestClick:function()
		{
			alert('Test1');
		},
		ChangeComponent: function (newCompName)
		{
			this.CleanUp();
			this.ClearPropAndEvents();
			if (!newCompName) {return;};
			var original = jsForms.Templates[newCompName];
			var newTemplate = jsForms.DesignMode.CreateDesignModeTemplate(original);
			this.P.SelectComponentDesign = $(newTemplate);
			jsForms.Templates[newCompName] = newTemplate;
			jsForms.CleanCache(newCompName);
			this.P.SelectComponent = jsForms.CreateComponent(newCompName,undefined,{designMode:true});
			jsForms.CleanCache(newCompName);
			jsForms.Templates[newCompName] = original;
			
			this.P.SelectComponent.addClass('EditComponent').hide().appendTo(this.C.Screen).Init().show();
			this.UpdateDOMInspector();
		},
		UpdateDOMInspector: function(){
			var tree = this.C.tvComponentDOM;
			tree.Clear();
			if (this.P.DOMInspector)
			{
				delete(this.P.DOMInspector);
			};
			if (!this.P.SelectComponentDesign) {
				return;
			}
			
			function addToParent(item)
			{
				if (item.p != undefined) {
					var parentNode = jobList[item.p].node;
					if (parentNode) {
						parentNode.AddChild(node);
					}
				}
			}
			
			var root = tree.CreateNode(0,'&lt;'+this.Properties.SelectComponent._Type+'&gt;');
			var obj = this.Properties.SelectComponentDesign;
			var objR = this.Properties.SelectComponent;
			var jobList = [
				{node:root,componentR:objR,isRoot:true},
				{
				e: obj[0],
				p:0,
				isRoot:true
				}];
			this.Properties.DOMInspector = jobList;
			var index = 1;
			
			function createContent(item){
				var listContent;
				if (item.componentR) {
					listContent = jsForms.DesignMode.GetContents(item.componentR._Type);
				}
				else {
					listContent = {};
				}

				function addContent(el,elName)
				{
					jobList.push({
						e: el,
						p: index,
						name: ' >['+elName+']',
						isContent: true
					});
					var cindex = jobList.length - 1;
					for (var i = 0; i < el.childNodes.length; i++) {
						//debugger;
						jobList.push({
							e: el.childNodes[i],
							p: cindex
						});
					}
				}
				var items = $('>content', item.elementD);
				for (var ii = 0; ii < items.length; ii++) {
					var contentName = items[ii].getAttribute('into');
					if (contentName == undefined || contentName == null || contentName == '') {
						contentName = 'content';
					}
					addContent(items[ii],contentName);
					if (listContent[contentName] != undefined) {
						delete (listContent[contentName]);
					}
				}
				for (var ii in listContent) {
					var el = $('<content into="'+ii+'"/>').appendTo(item.elementD)[0];
					addContent(el,ii);
				}
			}
			
			while (index< jobList.length)
			{
				var node = tree.CreateNode(index);
				var item = jobList[index];
				var nodeName;
				item.node =node;
				item.elementD = $(item.e);
				if (item.isContent==true)
				{
					node.SetText(item.name);
					addToParent(item);
					index++;
					continue;
				}

				item.tid = item.e.getAttribute('tid');
				if (item.tid != undefined && item.tid != null) {
						var element = $('[@tid="' + item.tid + '"]', objR);
						if (element.length != 0) {
							item.elementR = element;
						}
					}
					
				if (item.e.nodeType == 3 || (item.e.getAttribute('istext') != undefined && item.e.nodeName == "SPAN")) {
					//TextNode
					//SPAN #TEXT
					item.isText = true;
					nodeName = '#TEXT';
				}
				else {
					//Tag or Component
					var name = item.e.getAttribute('name');
					var type = item.e.getAttribute('type');
					if (item.e.tagName.toUpperCase() != "COMPONENT") {
						//Tag
						if (name != undefined && name != null) {
							nodeName = '&lt;' + item.e.nodeName + '&gt;[' + name + ']';
						}
						else {
							nodeName ='&lt;' + item.e.nodeName + '&gt;';
						}
					}
					else {
						//Component
						item.isComponent = true;
						if (item.elementR != undefined) {
							var compCurName = item.elementR.attr('name');
							if (compCurName != undefined && compCurName != null) {
								item.componentR = objR.Components[compCurName];
							}
						};
						
						if (name != undefined && name != null) {
							nodeName = '&lt;' + type + '&gt;[' + name + ']';
						}
						else {
							nodeName = '&lt;' + type + '&gt;';
						}
						createContent(item);
					}
				}
				
				if (item.isText != true && item.isComponent != true && item.e.nodeName !='SELECT') {
					for (var i = 0; i < item.e.childNodes.length; i++) {
						//debugger;
						jobList.push({
							e: item.e.childNodes[i],
							p: index
						});
					}
				}
				node.SetText(nodeName);
				addToParent(item);
				index++;
			}
			
			root.show();
			tree.AddChild(root);
		}
};